/*
 * Copyright (c) 2013. wyouflf (wyouflf@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lidroid.xutils.http.callback;

import android.util.Log;

import com.lidroid.xutils.util.IOUtils;
import com.lidroid.xutils.util.OtherUtils;

import org.apache.http.HttpEntity;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

public class StringDownloadHandler {

    public String handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String charset) throws IOException {
        if (entity == null) return null;

        long current = 0;
        long total = entity.getContentLength();
        byte[] content = null;
    	if (entity.getContentEncoding().toString().contains("fzip")) {//gzip
            BufferedInputStream bis = null;
            InputStreamReader reader = null;
            ByteArrayOutputStream baos = null;
            InputStream is = null;
            boolean isFzip = false;
            StringBuffer sb = new StringBuffer();
            try {
                is = entity.getContent();
                bis = new BufferedInputStream(is);
                bis.mark(2);
                byte[] header = new byte[2];
                int result = bis.read(header);
                bis.reset();
                int headerData = getShort(header);
                if (result != -1 && headerData == 0x1f8b) {
                    is = new GZIPInputStream(bis);
                    isFzip = true;
                } else {
                    isFzip = false;
                    is = bis;
                }
                int size = 5 * 1024;
                
                if (isFzip) {

                    reader = new InputStreamReader(is, "utf-8");

                    char[] data = new char[size];
                    int readSize;
                    


                    BufferedReader input = new BufferedReader(reader);
                    String s;
                    while ((s = input.readLine()) != null) {
                        sb.append(s);
                    }


                    content = sb.toString().getBytes();
                } 
                
//                else {
//                    byte[] data = new byte[size];
//                    int readSize;
//
//                    baos = new ByteArrayOutputStream();
//                    while ((readSize = is.read(data, 0, size)) > 0) {
//                        baos.write(data, 0, readSize);
//                    }
//                    content = baos.toByteArray();
//                }
                
//                LogcatUtil.LOG_D("isFzip is " + isFzip + " ,content.size:" + (content != null ? content.length : 0));
            } catch (Exception e) {
            	Log.d("http gzip", e.getMessage());
//                LogcatUtil.LOG_E("WebApiUtils.call.Err:" + e.getMessage());
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                    if (bis != null) {
                        bis.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                    if (is != null) {
                        is.close();
                    }


                } catch (IOException e) {
//                    LogcatUtil.LOG_E("WebApiUtils.call.IOExc.Err:" + e.getMessage());
                }
            }
            return sb.toString();
        }else{
        	if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
                return null;
            }

            InputStream inputStream = null;
            StringBuilder sb = new StringBuilder();
            try {
                inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append('\n');
                    current += OtherUtils.sizeOfString(line, charset);
                    if (callBackHandler != null) {
                        if (!callBackHandler.updateProgress(total, current, false)) {
                            break;
                        }
                    }
                }
                if (callBackHandler != null) {
                    callBackHandler.updateProgress(total, current, true);
                }
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
            return sb.toString().trim();
        }
        
    }
    private static int getShort(byte[] data) {
        return (int) ((data[0] << 8) | data[1] & 0xFF);
    }
}
